#!/usr/bin/env python

import test


class Dialog(object):
    """ docs """
    def __init__(self, uiElements):
        """ docs """
        
        # list of dictionary
        self.uiList = uiElements
        self.uiElementList = []
        for e in self.uiList:
            self.uiElementList.append( UIElement(e))
        
        self.code = ""
        
        self.Parse()
        return
    
    def LocateElement(self, key, value):
        
        # e is a UIElement       
        for e in self.uiElementList:
            if ( e.ui[key] == value):
                #print e.varName,"[",key,"]", e.ui[key], " == ",  value
                return e
        
        return None
    
    def Parse(self):
        
        for e in self.uiElementList:
            # find element whose Parent: value is equal to name
            parent = self.LocateElement("name", e.ui["Parent"])
            if(e != parent):            
                e.parent = parent
                #e.Debug()
        return
    
    def BuildCode(self):
        
        for e in self.uiElementList:
            self.code += e.Code()
        
        return self.code 

class UIElement(object):
    """ docs """
    def __init__(self, ui):
        """ docs """
        self.ui = ui
        self.quotedName = "\"" + self.ui['name'] + "\"" 

        self.varName = "_" + self.ui['name']
        self.parent = None
        self.code = ""
        
        return
    
    def __eq__(self, other):
        
        if(other == None):
            return False
        
        return self.ui["name"] == other.ui["name"]
        
    def __ne__(self, other):    
        if(other == None):
            return True
        return self.ui["name"] != other.ui["name"]
    
    def GetParentVarName(self):
        
        if(self.parent != None):
            return self.parent.varName
        
        return "this"
    
    def Debug(self):
        
        print "Parent of ", self.ui["name"], "is ", self.GetParentVarName()
        return  
    def Code(self):
        
        #_SelectorList001 = new CATDlgSelectorList(this, "SelectorList001");
        #self.code = self.ui['type'] + " *p" + "  new " + self.ui['type'] + "()"
        self.code = self.varName + " = new " + self.ui['type'] + "(" + self.GetParentVarName() + ", " + self.quotedName + ") ; \n"
        #_SelectorList001 -> SetGridConstraints(0, 0, 1, 1, CATGRID_4SIDES);
        self.code += self.varName + "-> SetGridConstraints(0, 0, 1, 1, CATGRID_4SIDES); \n"
        
        return  self.code
    
def Build():
    
    dlg = Dialog(test.DialogUI)
    
    print dlg.BuildCode()
        
    return

if __name__ == '__main__':
    Build()

